<!DOCTYPE html>
<html lang="zh-CN" th:replace="~{layout :: layout(~{::title}, ~{::main}, ~{::script})}">
<head>
    <title th:text="${site.title ?: '机械设备制造商'} + ' - 专业机械设备制造商'">机械设备制造商 - 首页</title>
</head>
<body>
    <main>
        <!-- 图片轮播组件 -->
        <section class="carousel-section">
            <div class="carousel-container">
                <!-- 轮播图片 -->
                <div class="carousel-slide active">
                    <img src="/themes/alibaba-b2b-theme/assets/images/carousel-1.jpg" 
                         alt="轮播图片1">
                </div>
                
                <div class="carousel-slide">
                    <img src="/themes/alibaba-b2b-theme/assets/images/carousel-2.jpg" 
                         alt="轮播图片2">
                </div>
                
                <div class="carousel-slide">
                    <img src="/themes/alibaba-b2b-theme/assets/images/carousel-3.jpg" 
                         alt="轮播图片3">
                </div>
                
                <!-- 导航按钮 -->
                <button class="carousel-nav carousel-prev">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                </button>
                
                <button class="carousel-nav carousel-next">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                    </svg>
                </button>
                
                <!-- 指示器 -->
                <div class="carousel-indicators">
                    <button class="carousel-indicator active" data-slide="0"></button>
                    <button class="carousel-indicator" data-slide="1"></button>
                    <button class="carousel-indicator" data-slide="2"></button>
                </div>
            </div>
        </section>

        <!-- 产品分类展示区域 -->
        <section class="product-categories">
            <div class="container">
                <div class="section-header">
                    <h2 class="section-title">主营产品分类</h2>
                    <p class="section-subtitle">专业制造各类工业机械设备，品质卓越，服务全球</p>
                </div>
                <div class="categories-grid" id="categories-grid">
                    <!-- 加载中提示 -->
                    <div class="loading-placeholder" id="categories-loading">
                        <div class="loading-spinner"></div>
                        <p>正在加载产品分类...</p>
                    </div>
                </div>
                <div class="view-all-products">
                    <a href="/products" class="btn btn-primary">查看全部产品 →</a>
                </div>
            </div>
        </section>

        <!-- 公司优势区域 -->
        <section class="company-advantages">
            <div class="container">
                <div class="section-header">
                    <h2 class="section-title">企业核心优势</h2>
                    <p class="section-subtitle">专业团队 · 先进设备 · 严格质控 · 完善服务</p>
                </div>
                <div class="advantages-grid">
                    <div class="advantage-card">
                        <div class="advantage-icon">
                            <i class="fas fa-industry"></i>
                        </div>
                        <h3 class="advantage-title">先进制造</h3>
                        <p class="advantage-desc">拥有现代化生产车间5000㎡，配备先进的数控设备和检测仪器</p>
                        <ul class="advantage-features">
                            <li>德国进口设备</li>
                            <li>自动化生产线</li>
                            <li>24小时生产能力</li>
                        </ul>
                    </div>
                    
                    <div class="advantage-card">
                        <div class="advantage-icon">
                            <i class="fas fa-certificate"></i>
                        </div>
                        <h3 class="advantage-title">质量认证</h3>
                        <p class="advantage-desc">通过ISO9001质量管理体系认证，产品符合国际标准</p>
                        <ul class="advantage-features">
                            <li>ISO9001认证</li>
                            <li>CE欧盟认证</li>
                            <li>SGS第三方检测</li>
                        </ul>
                    </div>
                    
                    <div class="advantage-card">
                        <div class="advantage-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <h3 class="advantage-title">专业团队</h3>
                        <p class="advantage-desc">拥有20年以上经验的工程师团队，提供专业技术支持</p>
                        <ul class="advantage-features">
                            <li>资深工程师团队</li>
                            <li>7×24技术支持</li>
                            <li>定制化解决方案</li>
                        </ul>
                    </div>
                    
                    <div class="advantage-card">
                        <div class="advantage-icon">
                            <i class="fas fa-globe"></i>
                        </div>
                        <h3 class="advantage-title">全球服务</h3>
                        <p class="advantage-desc">产品远销50多个国家和地区，建立完善的售后服务网络</p>
                        <ul class="advantage-features">
                            <li>全球50+国家</li>
                            <li>本地化服务</li>
                            <li>快速响应支持</li>
                        </ul>
                    </div>
                </div>
            </div>
        </section>

        <!-- 企业数据展示 -->
        <section class="company-stats">
            <div class="container">
                <div class="stats-grid">
                    <div class="stat-item">
                        <div class="stat-number">8+</div>
                        <div class="stat-label">年专业经验</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">500+</div>
                        <div class="stat-label">成功案例</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">50+</div>
                        <div class="stat-label">出口国家</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">99%</div>
                        <div class="stat-label">客户满意度</div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 联系咨询区域 -->
        <section class="contact-cta">
            <div class="container">
                <div class="cta-content">
                    <h2 class="cta-title">需要定制化机械设备解决方案？</h2>
                    <p class="cta-subtitle">我们的专业团队随时为您提供技术咨询和报价服务</p>
                    <div class="cta-buttons">
                        <a href="/contact" class="btn btn-primary btn-large">获取报价</a>
                        <a href="tel:+86-512-12345678" class="btn btn-outline btn-large">电话咨询</a>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <script>
        // 页面加载动画
        document.addEventListener('DOMContentLoaded', function() {
            // 企业横幅动画
            const banner = document.querySelector('.company-banner');
            if (banner) {
                banner.style.opacity = '0';
                banner.style.transform = 'translateY(-20px)';
                banner.style.transition = 'all 0.8s ease';
                
                setTimeout(() => {
                    banner.style.opacity = '1';
                    banner.style.transform = 'translateY(0)';
                }, 200);
            }
            
            // 加载产品分类数据
            loadProductTypes();
            
            // 数字统计动画
            const statNumbers = document.querySelectorAll('.stat-number');
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const target = entry.target;
                        const finalValue = target.textContent;
                        animateNumber(target, finalValue);
                        observer.unobserve(target);
                    }
                });
            });
            
            statNumbers.forEach(number => {
                observer.observe(number);
            });
        });
        
        // 加载产品分类数据
        async function loadProductTypes() {
            const apiEndpoints = [
                '/apis/content.halo.run/v1alpha1/product-types?size=8',
                '/apis/content.halo.run/v1alpha1/product-types'
            ];
            
            for (const endpoint of apiEndpoints) {
                try {
                    console.log('尝试API端点:', endpoint);
                    const response = await fetch(endpoint);
                    
                    if (!response.ok) {
                        console.log(`API端点 ${endpoint} 返回状态: ${response.status}`);
                        if (response.status === 302 || response.status === 401 || response.status === 403) {
                            console.log('API需要认证或权限，跳过此端点');
                        }
                        continue;
                    }
                    
                    const data = await response.json();
                    console.log('API数据:', data);
                    
                    if (data.items && data.items.length > 0) {
                        // 按优先级降序排序，然后取前8个
                        const sortedItems = data.items
                            .sort((a, b) => {
                                const priorityA = (a.spec?.priority || a.priority || 0);
                                const priorityB = (b.spec?.priority || b.priority || 0);
                                return priorityB - priorityA;
                            })
                            .slice(0, 8);
                        renderProductTypes(sortedItems);
                        return;
                    } else if (data.length > 0) {
                        // 按优先级降序排序，然后取前8个
                        const sortedItems = data
                            .sort((a, b) => {
                                const priorityA = (a.spec?.priority || a.priority || 0);
                                const priorityB = (b.spec?.priority || b.priority || 0);
                                return priorityB - priorityA;
                            })
                            .slice(0, 8);
                        renderProductTypes(sortedItems);
                        return;
                    }
                } catch (error) {
                    console.error(`API端点 ${endpoint} 失败:`, error);
                    continue;
                }
            }
            
            console.log('所有API端点都失败，使用备用数据');
            renderFallbackCategories();
        }
        
        // 渲染产品分类
        function renderProductTypes(productTypes) {
            const grid = document.getElementById('categories-grid');
            const loading = document.getElementById('categories-loading');
            
            if (loading) {
                loading.remove();
            }
            
            if (!productTypes || productTypes.length === 0) {
                renderFallbackCategories();
                return;
            }
            
            productTypes.forEach((productType, index) => {
                const card = createProductTypeCard(productType, index);
                grid.appendChild(card);
            });
            
            // 触发动画
            setTimeout(() => {
                animateProductCards();
            }, 100);
        }
        
        // 创建产品分类卡片
        function createProductTypeCard(productType, index) {
            const card = document.createElement('div');
            card.className = 'category-card';
            
            // 兼容不同的数据格式
            const spec = productType.spec || productType;
            const status = productType.status || {};
            
            const displayName = spec.displayName || productType.displayName || '未命名分类';
            const description = spec.description || productType.description || '优质产品，专业服务';
            const images = spec.images || productType.images || [];
            const priority = spec.priority || productType.priority || 0;
            const productCount = status.productCount || productType.productCount || 0;
            const categoryName = productType.metadata?.name || '';
            
            const firstImage = images.length > 0 
                ? getImageUrl(images[0])
                : getPlaceholderImage(displayName);
            
            card.innerHTML = `
                <div class="category-image">
                    <img src="${firstImage}" alt="${displayName}" loading="lazy" style="cursor: pointer;">
                </div>
                <div class="category-info">
                    <h3 class="category-title">${displayName}</h3>
                    <p class="category-desc">${description}</p>
                    <div class="category-stats">
                        <span class="stat-item">${productCount > 0 ? productCount + '个产品' : '精选产品'}</span>
                        <span class="stat-item">优先级 ${priority}</span>
                    </div>
                </div>
            `;
            
            // 添加点击事件跳转到产品页面
            card.style.cursor = 'pointer';
            card.addEventListener('click', function() {
                if (categoryName) {
                    window.location.href = `/products?category=${encodeURIComponent(categoryName)}`;
                } else {
                    window.location.href = '/products';
                }
            });
            
            return card;
        }
        
        // 获取图片URL（添加/upload前缀）
        function getImageUrl(url) {
            if (!url) return '';
            if (url.startsWith('http://') || url.startsWith('https://')) {
                return url;
            }
            if (url.startsWith('/upload/')) {
                return url;
            }
            return '/upload/' + url;
        }
        
        // 获取占位图片
        function getPlaceholderImage(categoryName) {
            const placeholderMap = {
                '数控机床': 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=industrial%20CNC%20machining%20center%20machine%20in%20modern%20factory%20workshop%2C%20professional%20lighting%2C%20blue%20industrial%20style&image_size=landscape_4_3',
                '液压设备': 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=hydraulic%20press%20machine%20industrial%20equipment%20in%20factory%2C%20heavy%20duty%20machinery%2C%20blue%20industrial%20lighting&image_size=landscape_4_3',
                '自动化设备': 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=automated%20production%20line%20conveyor%20system%20in%20modern%20industrial%20factory%2C%20robotic%20automation%2C%20blue%20lighting&image_size=landscape_4_3',
                '模具设备': 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=precision%20mold%20and%20die%20manufacturing%20tools%20in%20workshop%2C%20high%20precision%20metalworking%2C%20industrial%20blue%20theme&image_size=landscape_4_3',
                '激光切割设备': 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=industrial%20laser%20cutting%20machine%20in%20modern%20metalworking%20workshop%2C%20high%20precision%20beam%2C%20blue%20industrial%20lighting&image_size=landscape_4_3',
                '焊接设备': 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=automated%20robotic%20welding%20equipment%20in%20industrial%20factory%2C%20sparks%20flying%2C%20blue%20workshop%20lighting&image_size=landscape_4_3'
            };
            
            return placeholderMap[categoryName] || 'https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=industrial%20machinery%20equipment%20professional%20blue%20theme&image_size=landscape_4_3';
        }
        
        // 产品分类卡片动画
        function animateProductCards() {
            const categoryCards = document.querySelectorAll('.category-card');
            categoryCards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(30px)';
                card.style.transition = 'all 0.6s ease';
                
                setTimeout(() => {
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, 400 + index * 100);
            });
        }
        
        // 渲染备用产品分类（当API失败时使用）
        function renderFallbackCategories() {
            const grid = document.getElementById('categories-grid');
            const loading = document.getElementById('categories-loading');
            
            if (loading) {
                loading.remove();
            }
            
            const fallbackCategories = [
                {
                    displayName: '数控机床',
                    description: '高精度CNC加工中心、车床、铣床等精密加工设备',
                    images: [],
                    productCount: 15,
                    priority: 100
                },
                {
                    displayName: '液压设备',
                    description: '液压机、液压站、液压缸等重型机械设备',
                    images: [],
                    productCount: 12,
                    priority: 90
                },
                {
                    displayName: '自动化设备',
                    description: '生产线、输送设备、机器人集成系统',
                    images: [],
                    productCount: 8,
                    priority: 80
                },
                {
                    displayName: '模具设备',
                    description: '注塑模具、冲压模具、精密工装夹具',
                    images: [],
                    productCount: 10,
                    priority: 70
                },
                {
                    displayName: '激光切割设备',
                    description: '高功率激光切割机、雕刻机等精密加工设备',
                    images: [],
                    productCount: 6,
                    priority: 60
                },
                {
                    displayName: '焊接设备',
                    description: '自动化焊接机、机器人焊接系统',
                    images: [],
                    productCount: 9,
                    priority: 50
                }
            ];
            
            fallbackCategories.forEach((category, index) => {
                const card = createProductTypeCard(category, index);
                grid.appendChild(card);
            });
            
            setTimeout(() => {
                animateProductCards();
            }, 100);
        }
        
        function animateNumber(element, finalValue) {
            const isPercentage = finalValue.includes('%');
            const isPlus = finalValue.includes('+');
            const numericValue = parseInt(finalValue.replace(/[^0-9]/g, ''));
            
            let currentValue = 0;
            const increment = numericValue / 50;
            const timer = setInterval(() => {
                currentValue += increment;
                if (currentValue >= numericValue) {
                    currentValue = numericValue;
                    clearInterval(timer);
                }
                
                let displayValue = Math.floor(currentValue);
                if (isPercentage) displayValue += '%';
                if (isPlus) displayValue += '+';
                
                element.textContent = displayValue;
            }, 30);
        }
        
        console.log('外贸机械公司主题首页加载成功！');
    </script>
</body>
</html>